/*
 * @Descripttion: 创建 axios 实例
 * @version: 1.0
 * @Author: 自由如风
 * @Date: 2021-05-28 12:11:02
 * @LastEditors: 自由如风
 * @LastEditTime: 2021-07-02 23:00:09
 */
import { AxiosRequestConfig, AxiosResponse } from 'axios'
import _axios from 'axios'
import { WX } from '..'

export class WXResponceError extends Error {
    constructor(public message: string, public code: number) {
        super()
    }
}

/**
 * 创建一个适用于微信公众号的axios实例微信实例
 * @param wx 微信实例
 * @returns 
 */
export function create_axios(wx?: WX, config?: AxiosRequestConfig) {
    const axios = _axios.create(config)

    axios.interceptors.request.use(function (request: AxiosRequestConfig) {
        if (!!wx?.access_token) {
            request.params = { access_token: wx?.access_token, ...request.params };
        }

        return request;
    })

    axios.interceptors.response.use(function (response: AxiosResponse) {
        // 拥有errcode 参数 ，且不为 0（成功）
        if (!!response.data.errcode && response.data.errcode != 0) {
            const e = response.data as { errmsg: string, errcode: number }
            throw new WXResponceError(e.errmsg, e.errcode); // 抛出异常
        }
        return response.data; // 
    })

    return axios;
}